package com.sync.platform.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sync.platform.common.Result;
import com.sync.platform.entity.ServerConfig;
import com.sync.platform.service.ServerConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

/**
 * Server management controller
 */
@Controller
@RequestMapping("/server")
public class ServerController {

    @Autowired
    private ServerConfigService serverConfigService;

    /**
     * Server list page
     */
    @GetMapping
    public String list(Model model) {
        LambdaQueryWrapper<ServerConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(ServerConfig::getCreateTime);
        model.addAttribute("servers", serverConfigService.list(queryWrapper));
        model.addAttribute("pageTitle", "同步平台 - 服务器管理");
        return "server/list";
    }

    /**
     * Add server page
     */
    @GetMapping("/add")
    public String add(Model model) {
        model.addAttribute("server", new ServerConfig());
        model.addAttribute("pageTitle", "同步平台 - 添加服务器");
        return "server/edit";
    }

    /**
     * Edit server page
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable Long id, Model model) {
        ServerConfig server = serverConfigService.getById(id);
        if (server == null) {
            return "redirect:/server";
        }

        model.addAttribute("server", server);
        model.addAttribute("pageTitle", "同步平台 - 编辑服务器");
        return "server/edit";
    }

    /**
     * Save server
     */
    @PostMapping("/save")
    @ResponseBody
    public Result<?> save(@RequestBody ServerConfig serverConfig) {
        boolean success = serverConfigService.saveOrUpdate(serverConfig);
        return success ? Result.success() : Result.fail("保存失败");
    }

    /**
     * Delete server
     */
    @DeleteMapping("/{id}")
    @ResponseBody
    public Result<?> delete(@PathVariable Long id) {
        boolean success = serverConfigService.removeById(id);
        return success ? Result.success() : Result.fail("删除失败");
    }

    /**
     * Test server connection
     */
    @PostMapping("/test")
    @ResponseBody
    public Result<?> test(@RequestBody ServerConfig serverConfig) {
        boolean success = serverConfigService.testConnection(serverConfig);
        return success
                ? Result.success("连接成功")
                : Result.fail("连接失败，请检查服务器配置");
    }

    /**
     * Update server status
     */
    @PutMapping("/{id}/status")
    @ResponseBody
    public Result<?> updateStatus(@PathVariable Long id, @RequestParam Integer status) {
        boolean success = serverConfigService.updateStatus(id, status);
        return success ? Result.success() : Result.fail("更新状态失败");
    }
}
